package gold.digger;

import gold.vo.TreeNode;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC508 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public Map<TreeNode, Integer> map = new HashMap<>();

        public int[] findFrequentTreeSum(TreeNode root) {
            if (null == root) return new int[0];
            getTreeSumRecur(root);

            Map<Integer, Integer> countMap = new LinkedHashMap<>();
            for (Map.Entry<TreeNode, Integer> treeNodeIntegerEntry : map.entrySet()) {
                int curSum = treeNodeIntegerEntry.getValue();
                if (countMap.containsKey(curSum)) countMap.put(curSum, countMap.get(curSum) + 1);
                else countMap.put(curSum, 1);
            }

            int maxCount = Integer.MIN_VALUE;
            for (Integer sum : countMap.keySet()) {
                if (countMap.get(sum) > maxCount) maxCount = countMap.get(sum);
            }

            List<Integer> list = new ArrayList<>();
            for (Integer sum : countMap.keySet()) {
                if (countMap.get(sum) == maxCount) list.add(sum);
            }

            int[] res = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                res[i] = list.get(i);
            }
            return res;
        }

        public int getTreeSumRecur(TreeNode root) {
            if (null == root) return 0;
            if (map.containsKey(root)) return map.get(root);
            int curSum = getTreeSumRecur(root.left) + getTreeSumRecur(root.right) + root.val;
            map.put(root, curSum);
            return curSum;
        }
    }

    public void run() {
        Solution solution = new Solution();
        TreeNode root = TreeNode.createTree("[3,1,5,0,2,4,6,null,null,null,3]");
        System.out.println(solution.findFrequentTreeSum(root));
    }

    public static void main(String[] args) throws Exception {
        LC508 an = new LC508();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
